<template>
  <div class="work-container">
    <el-row :gutter="20">
      <!-- 左上角分析栏 -->
      <el-col :span="12">
        <el-card>
          <el-row :span="12" :gutter="20">
            <el-col :span="8">
              <el-card>
                检测结果
              </el-card>
            </el-col>
            <el-col :span="16">
              <el-card>
                <div id="bar-chart" style="width: 100%; height: 180px;"></div>
              </el-card>
            </el-col>
          </el-row>
          <el-row :span="12" style="width: 100%;margin-top: 20px;">
            <el-col :span="24">
              <el-card style="background-color: rgb(209.4, 236.7, 195.9);padding: 10px;">
                <h4>针对当前情绪的建议</h4>
              </el-card>
            </el-col>
          </el-row>
          <template #footer ref="testData">
            <h6 class="analysis-footer">
              {{ testData }}
            </h6>
          </template>
        </el-card>
      </el-col>

      <!-- 右上角情绪建议 -->
      <el-col :span="12">
        <el-card>
          <div id="emotion-summary-chart" style="width: 100%; height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card>
          <div>
            <h3>本月情绪汇总</h3>
            <div class="summary-flex">
              <div class="daily-scroll">
                <div class="daily-charts">
                  <div v-for="(day, idx) in dailySummary" :key="day.date" class="daily-chart-item">
                    <div :id="'daily-chart-' + idx" class="daily-chart"></div>
                    <div class="daily-date">{{ day.date }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { listRecords } from '@/api/emotion/records'

const videoRef = ref(null)
const cameraOpened = ref(false)
const recordsList = ref([])
const dailySummary = ref([])
const testData = ref("检测时间：2025-05-21 15:14:47")

const suggestion = ref("（此处为情绪建议模块，暂未实现）")

function openCamera() {
  cameraOpened.value = true
  navigator.mediaDevices.getUserMedia({ video: true })
    .then(stream => {
      videoRef.value.srcObject = stream
    })
    .catch(err => {
      cameraOpened.value = false
      alert('无法打开摄像头: ' + err)
    })
}

// 获取本月的起止日期
function getMonthRange() {
  const now = new Date()
  const firstDay = new Date(now.getFullYear(), now.getMonth(), 1)
  const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0)
  return [
    firstDay.toISOString().slice(0, 10),
    lastDay.toISOString().slice(0, 10)
  ]
}

// 查询本月情绪记录
function getMonthRecords() {
  const [beginTime, endTime] = getMonthRange()
  listRecords({ pageNum: 1, pageSize: 999, beginTime, endTime }).then(res => {
    recordsList.value = res.rows || []
    nextTick(() => {
      renderSummaryChart()
      renderDailyCharts()
      renderBarChart()
    })
  })
}

// 统计情绪分布
function getEmotionSummary() {
  const summary = {}
  recordsList.value.forEach(record => {
    if (record.emotionPercentage) {
      record.emotionPercentage.split(',').forEach(item => {
        const [name, value] = item.split(':')
        summary[name.trim()] = (summary[name.trim()] || 0) + parseFloat(value)
      })
    }
  })
  // 取平均
  const count = recordsList.value.length
  Object.keys(summary).forEach(key => {
    summary[key] = count ? (summary[key] / count).toFixed(2) : 0
  })
  return summary
}

// 统计每日情绪分布
function getDailySummary() {
  const map = {}
  recordsList.value.forEach(record => {
    const date = record.createdAt?.slice(0, 10)
    if (!date) return
    if (!map[date]) map[date] = { date, summary: {}, count: 0 }
    if (record.emotionPercentage) {
      record.emotionPercentage.split(',').forEach(item => {
        const [name, value] = item.split(':')
        map[date].summary[name.trim()] = (map[date].summary[name.trim()] || 0) + parseFloat(value)
      })
      map[date].count++
    }
  })
  // 取平均
  return Object.values(map).sort((a, b) => a.date.localeCompare(b.date)).map(day => {
    Object.keys(day.summary).forEach(key => {
      day.summary[key] = day.count ? (day.summary[key] / day.count).toFixed(2) : 0
    })
    return day
  })
}

// 渲染本月饼图
function renderSummaryChart() {
  const chartDom = document.getElementById('emotion-summary-chart')
  if (!chartDom) return
  const myChart = echarts.init(chartDom)
  const summary = getEmotionSummary()
  const data = Object.keys(summary).map(key => ({
    name: key,
    value: summary[key]
  }))
  myChart.setOption({
    tooltip: { trigger: 'item' },
    legend: { bottom: 0, orient: "horizontal" },
    series: [{
      name: '本月情绪分布',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
      label: { show: true, formatter: '{b}: {c}%' },
      data
    }]
  })
}

// 渲染每日环形图
function renderDailyCharts() {
  dailySummary.value = getDailySummary()
  nextTick(() => {
    dailySummary.value.forEach((day, idx) => {
      const chartDom = document.getElementById('daily-chart-' + idx)
      if (!chartDom) return
      const myChart = echarts.init(chartDom)
      const data = Object.keys(day.summary).map(key => ({
        name: key,
        value: day.summary[key]
      }))
      myChart.setOption({
        tooltip: { trigger: 'item' },
        series: [{
          name: '情绪组成',
          type: 'pie',
          radius: ['60%', '80%'],
          avoidLabelOverlap: false,
          label: { show: false },
          data
        }]
      })
    })
  })
}

// 渲染柱状图
function renderBarChart() {
  dailySummary.value = getDailySummary()
  nextTick(() => {
    dailySummary.value.forEach((day, idx) => {
      const chartDom = document.getElementById('bar-chart')
      if (!chartDom) return
      const myChart = echarts.init(chartDom)
      const data = Object.keys(day.summary).map(key => ({
        name: key,
        value: day.summary[key]
      }))
      myChart.setOption({
        xAxis: {
          type: "value",
          axisTick: { show: true }, //是否显示坐标轴刻度
          axisLine: {
            show: true, //是否显示坐标轴轴线
          },
        },
        yAxis: {
          type: "category",
          data: data.map(item => item.name),
        },
        grid: { left: '1%', right: '1%', top: '2  %', bottom: 0, containLabel: true },
        series: [{
          name: '情绪组成',
          type: 'bar',
          avoidLabelOverlap: false,
          label: { show: false },
          data
        }]
      })
    })
  })
}

onMounted(() => {
  getMonthRecords()
})
</script>

<style scoped>
.work-container {
  padding: 20px;
}
.camera-section {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.advice-section {
  min-height: 120px;
}
.advice-placeholder {
  color: #bbb;
  margin-top: 20px;
}
.summary-flex {
  display: flex;
  align-items: flex-start;
}
.daily-scroll {
  overflow-x: auto;
  width: 100%;
  padding-left: 20px;
}
.daily-charts {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
}
.daily-chart-item {
  margin-right: 24px;
  text-align: center;
}
.daily-chart {
  width: 200px;
  height: 200px;
  margin-bottom: 8px;
  display: inline-block;
}
.daily-date {
  font-size: 14px;
  color: #666;
}
.analysis-footer {
  text-align: center;
  margin: 0;
  padding: 0;
}
</style>